<?php
/**
 * 微信支付
 * User: liujb
 * Date: 2017/2/16
 * Time: 9:01
 */

namespace Api\Controller;
//include 'wechatAppPay.class.php';

class WechatController  extends ApiController
{
    public  function  wechpay(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);

        params_exist(array('invite_id'));
        $invite_id  =$_POST['invite_id'];

        $invite = M('invite')->where('id='.$invite_id)->find();

        if($invite){
            $amount = M('invite_fee')->getField('money');
        }else{
            response('-9','','没有查到发布的需求');
        }
        import('Vendor.Weixinpay.WechatAppPay');
        //统一下单方法
        $wechatAppPay = new \wechatAppPay();
        $params['body'] = '支付订单';						//商品描述
        $trade_no = build_order_no();
        $params['out_trade_no'] = $trade_no;	//自定义的订单号
        $params['total_fee'] = $amount*100;					//订单金额 只能为整数 单位为分
        $params['trade_type'] = 'APP';					//交易类型 JSAPI | NATIVE | APP | WAP
        $result = $wechatAppPay->unifiedOrder( $params );
        //print_r($result);
        //创建APP端预支付参数
        /** @var TYPE_NAME $result */
        $wxdata = @$wechatAppPay->getAppPayParams($result['prepay_id'] );
        //print_r ($wxdata);
        $data = array(
            'uid'           =>  API_UID,
            'order_no'     => $trade_no,
            'amount'       =>$amount,
            'status'       => 0,
            'create_time'     => NOW_TIME,
            'invite_id'    =>$invite_id,
            'type'          => 2
        );

        $recharge = M('recharge_order');
        $InsertId   = $recharge->add($data);
        if ($InsertId){
            response(200,$wxdata,'');
        }else{
            response(-2);
        }
       // $InsertId   = $recharge->add($data);

    }

    /**
     * 微信支付通知接口
     */
    public function notify(){
        $xmldata = file_get_contents("php://input");
        file_put_contents('./xmldata.txt', $xmldata);
        libxml_disable_entity_loader(true);
        $data = (array)simplexml_load_string($xmldata, 'SimpleXMLElement', LIBXML_NOCDATA);
        file_put_contents('./wx.txt', json_encode($data));

       import('Vendor.Weixinpay.WechatAppPay');
       $wechatAppPay = new \wechatAppPay();
        //$data = $wechatAppPay->getNotifyData();

        if($data) {
            $out_trade_no = $data['out_trade_no'];//订单号
            $money = $data['total_fee'] / 100;  //充值金额

            //观看视频支付回调
            $Users = M('users','cmf_');
            $Config =  M('config_private','cmf_');
            $config = $Config->where('id=1')->find();
            $Video = M('video','cmf_');

            $Purcase = M('purchase','cmf_');
            $maps['order_no'] = $out_trade_no;
            $maps['status'] = 0;
            $maps['money'] =  rtrim(rtrim($money, '0'), '.');;
            $pur_res = $Purcase->where($maps)->find();
            $video = $Video->where('id='.$pur_res['vid'])->find();
            if($pur_res){
                $data['status'] =1;
                $data['uptime'] = time();
                $pur_res1 = $Purcase->where($maps)->save($data);
                if($pur_res1) {
                    //消费记录
                    payrecord($pur_res['uid'],$pur_res['id'],$pur_res['money'],11,1);
                    //系统抽成
                    $watch_ratio = $pur_res['coin']*$config['watch_ratio']/100;
                    $coin2= $pur_res['coin']-$watch_ratio;
                    //推荐抽成
                    if($video['is_recommend']){
                        $Experlevel=M("experlevel",'cmf_');
                        $experience=$Users->where("id=".$video['uid'])->getField("consumption");
                        $level=$Experlevel->where("level_up>='$experience'")->order("levelid asc")->find();
                        $level_ratio= $pur_res['coin']*$level['recommend_ratio']/100;
                        $coin2= $coin2-$level_ratio;
                    }
                    //给上传者播豆
                    $Users->where('id='.$video['uid'])->setInc('votes',$coin2);
                    //上传者消费记录
                    payrecord($video['uid'],0,$coin2,14,2);
                    echo 'SUCCESS';
                }
            }

            //推荐视频支付回调
            $Download = M('recommend_video','cmf_');
            $down_res=$Download->where($maps)->find();
            if($down_res){
                $video = $Video->where('id='.$down_res['vid'])->find();

                $data['status'] =1;
                $data['uptime'] = time();
                $down_res1=$Download->where($maps)->save($data);
                if($down_res1){
                    //消费记录
                    payrecord($down_res['uid'],$down_res['id'],$down_res['money'],15,1);
                    //系统抽成
                    $watch_ratio = $down_res['coin']*$config['download_ratio']/100;
                    $coin2= $down_res['coin']-$watch_ratio;

                    $Video->where('id='.$down_res['vid'])->setField('rec_level',$down_res['level']);
                    //给上传者播豆
                    $Users->where('id='.$video['uid'])->setInc('votes',$coin2);
                    //上传者消费记录
                    payrecord($video['uid'],0,$coin2,14,2);
                    echo 'SUCCESS';
                }
            }

            //打赏视频支付回调
            $Reward = M('reward','cmf_');
            $reward_res = $Reward->where($maps)->find();
            if($reward_res){
                $video = $Video->where('id='.$reward_res['vid'])->find();

                $data['status'] = 1;
                $data['uptime'] = time();
                $reward_res1=$Reward->where($maps)->save($data);
                if($reward_res1){
                    //消费记录
                    payrecord($reward_res['uid'],$reward_res['id'],$reward_res['money'],13,1);
                    //系统抽成
                    $watch_ratio = $reward_res['coin']*$config['reward_ratio']/100;
                    $coin2= $reward_res['coin']-$watch_ratio;
                    //给上传者播豆
                    file_put_contents('./coin.txt', json_encode($coin2));
                    file_put_contents('./uid.txt', json_encode($video['uid']));

                    $Users->where('id='.$video['uid'])->setInc('votes',$coin2);
                    //上传者消费记录
                    payrecord($video['uid'],0,$coin2,14,2);
                    echo 'SUCCESS';
                }
            }

            $where['order_no'] = $out_trade_no;
            $where['price'] = $money;
            $where['pay_status'] = 0;
            $res = M('order')->where($where)->find();
            $order_id = M('order')->where($where)->getField('id');

            if ($res) {
                $res['trade_no'] = $out_trade_no;
                $res['total_fee'] = $money;
                D('order')->pay($res,30);
                M('order_product')->where(array('order_id' => $order_id))->save(array('create_time' => time(), 'update_time' => time()));
                $productid_result = M('order_product')->field('product_id')->where(array('order_id' => $order_id))->find();
                //接收通知成功后应答输出
                $wechatAppPay->replyNotify();
                if (!empty($productid_result)) {
                    $userid_result = M('product')->field('uid')->where(array('id' => $productid_result['product_id']))->find();
                    if (!empty($userid_result)) {
                        $phone_result = M('ucenter_member')->field('username')->where(array('id' => $userid_result['uid']))->find();
                        $sales = M('product')->where(array('id' => $productid_result['product_id']))->getField('sales');
                        //M('product')->where(array('id' => $productid_result['product_id']))->save(array('sales' => intval($sales) + 1));
                        file_put_contents('order.txt', json_encode($phone_result));
                        Message::send($phone_result['username'], '#code#=' . $out_trade_no, '45315');
                    }

                }

            }
        }
    }
}